<template>
    <div class="article-post-box">
        <!--        标题-->
        <div class="article-title-part">
            <el-input v-model="article.title" placeholder="请输入标题(1-64个字)" maxlength="64"
                      show-word-limit
                      minlength="1"></el-input>
        </div>
        <!--        内容编辑部分-->
        <div class="article-post-part">
            <mavon-editor v-model="article.content"
                          ref="editor"
                          @onImageClick="onEditorImageClick"
                          @change="onContentChange"/>
        </div>
        <!--  文章设置, 分类，封面，标签-->
        <div class="article-post-settings-part">
            <el-form :ref="this.formName" :model="article" label-width="80px">
                <el-form-item label="文章分类" label-width="80px" prop="categoryId"
                              :rules="[{ required:true, message: '请选择分类',trigger: 'blur'}]">
                    <el-select v-model="article.categoryId"
                               size="small" placeholder="请选择分类">
                        <el-option
                            v-for="item in categories"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="摘要" label-width="80px" prop="summary"
                              :rules="[{ required:true, message: '请输入摘要',trigger: 'blur'}]">
                    <el-input v-model="article.summary" type="textarea" placeholder="请输入文章摘要"
                              :rows="2"
                              resize="none"></el-input>
                </el-form-item>
                <el-form-item label="封面"
                              :rules="[{ required:true, message: '请选择封面',trigger: 'blur'}]"
                              prop="cover">
                    <div
                        class="avatar-uploader avatar-box"
                        @click="choiceArticleCover()">
                        <img v-if="article.cover" :src="article.cover" class="avatar-box">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </div>
                </el-form-item>

                <el-form-item label="标签"
                              :rules="[{ required:true, message: '请输入标签',trigger: 'blur'}]"
                              prop="label">
                    <el-tag :key="tag"
                            v-for="tag in labels"
                            closable
                            :disable-transitions="false"
                            @close="deleteLabel(tag)"
                            style="margin-right: 20px">
                        {{ tag }}
                    </el-tag>

                    <el-input class="input-new-tag"
                              v-if="labelInputVisible"
                              v-model="labelNewValue"
                              ref="saveTagInput"
                              @keyup.enter.native="handleLabelInputConfirm()"
                              placeholder="添加新的标签"
                              style="width: 250px">
                    </el-input>

                    <el-button v-else class="button-new-tag" type="small"
                               @click="showAddLabelWindow()">添加标签
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <!--        发布/草稿预览的按钮-->
        <div class="article-post-action-bar">
            <div class="article-btn-container">
                <el-button :plain="true" @click="preView()">全屏预览</el-button>
                <el-button :plain="true" @click="saveArticleDraft()"
                           v-show="article.state=== ''">保存草稿
                </el-button>
                <el-button type="primary" @click="publicArticle()"
                           v-if="article.state==='2' || article.state === ''">发表文章
                </el-button>
                <el-button type="primary" @click="postAndPutArticle()"
                           v-else>更新文章
                </el-button>
            </div>
        </div>

        <div class="article-post-dialog-box">
            <!--            上传图片的弹窗-->
            <el-dialog
                :fullscreen="true"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                title="图片选择"
                :visible.sync="dialogVisible"
                @close="handleClose()"
            >
                <span>选择你要使用的图片，上传自己的图片</span>
                <div class="image-action-bar">
                    <el-upload
                        accept="image/*"
                        class="avatar-uploader"
                        :action="'/admin/image/' + imageSelectFor"
                        :show-file-list="false"
                        :on-success="handleArticleSuccess"
                        :before-upload="beforeAvatarUpload">
                        <el-button type="primary" style="margin: 10px">上传图片</el-button>
                    </el-upload>
                </div>

                <!--                图片展示部分-->
                <div class="image-selector-list">
                    <el-radio-group v-model="selectedImageIndex"
                                    fill="#8c939d">
                        <el-radio-button :label="index"
                                         v-for="(item, index) in articleImages" :key="index">
                            <el-image
                                :src="'/portal/image/' + item.url"
                                class="image-list-style">

                            </el-image>
                        </el-radio-button>
                    </el-radio-group>
                </div>


                <!--                图片分页部分-->
                <div class="page-navigation-box">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pageNavigation.currentPage"
                        :page-sizes="[5, 10]"
                        :page-size="pageNavigation.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pageNavigation.totalElements">
                    </el-pagination>
                </div>

                <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="onImageSelected">确 定</el-button>
                </span>
            </el-dialog>

            <!--            提示未保存的弹窗-->
            <el-dialog
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                title="确认要离开吗？"
                :visible.sync="saveConfirmDialogVisible"
                width="30%">
                <span>系统可能不会保存您所做的更改。</span>
                <span slot="footer" class="dialog-footer">
                <el-button @click="saveConfirmDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="toNextPage()">确 定</el-button>
              </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import {listCategories} from "@/api/categoryAdminApi";
import {success_code} from "@/utils/ResponseState";
import {listImages} from "@/api/image-admin-api";
import editor from '../../../lib/mavon-editor/mavon-editor'
import '../../../lib/mavon-editor/css/index.css'
import Vue from 'vue'
import {getArticle, postArticle, putArticle} from "@/api/article-admin-api";
import {db_draft_state_article, db_publish_status} from "@/utils/LRConstant";

Vue.use(editor);

export default {
    name: "post-article",
    data() {
        return {
            nextPath: '',
            isContentSave: false,
            imageSelectFor: 'article',
            selectedImageIndex: '',
            dialogVisible: false,
            saveConfirmDialogVisible: false,
            labelInputVisible: false,
            labels: [],
            categories: [],
            formName: 'post-article',
            article: {
                title: '',
                content: '',
                id: "",
                userId: "",
                userAvatar: null,
                userName: "",
                categoryId: "",
                type: "1",
                state: '',
                summary: "",
                label: "",
                viewCount: 0,
                createTime: "2020-10-02T07:19:06.000+0000",
                updateTime: "2020-10-02T07:19:06.000+0000",
                cover: ""
            },
            labelNewValue: '',
            // 分页需要的数据
            pageNavigation: {
                currentPage: 1,
                totalPages: 1,
                pageSize: 5,
                totalElements: 10
            },
            articleImages: []
        }
    },
    methods: {
        // 删除label
        onImageSelected() {
            // console.log(this.selectedImageIndex);

            let articleImage = this.articleImages[this.selectedImageIndex];

            if (this.imageSelectFor === 'cover') {

                this.article.cover = "/portal/image/" + articleImage.url;
            } else if (this.imageSelectFor === 'article') {
                this.$refs.editor.toolbar_left_addlink('no-link', articleImage.name, "/portal/image/" + articleImage.url)
            }

            // change ui
            this.dialogVisible = false;
        },
        deleteLabel(tag) {
            this.labels.splice(this.labels.indexOf(tag), 1);

            if (this.labels.length < 5) {
                this.labelInputVisible = false;
            }
        },
        handleLabelInputConfirm() {
            // check data
            if (this.labelNewValue === '') {
                this.$message.warning("标签不能为空");
                return;
            }
            // 回车的时候
            if (this.labels.length < 5) {
                this.labels.push(this.labelNewValue);
                this.labelNewValue = '';
            }

            if (this.labels.length >= 5) {
                this.labelInputVisible = false;
            }
        },
        showAddLabelWindow() {
            // check data
            // 限制只能添加5个label
            this.labelInputVisible = this.labels.length < 5;
        },
        // 图片上传后
        handleAvatarSuccess(response) {
            if (response.code === success_code) {
                this.$message.success(response.message);

                this.article.cover = '/portal/image/' + response.data.path;
            } else {
                this.$message.error(response.message);
            }
        },
        handleArticleSuccess(response) {
            if (response.code === success_code) {
                this.$message.success(response.message);

                this.listImages();
            } else {
                this.$message.error(response.message);
            }
        },
        // 图片上传前
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 6;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        // 文章编辑部分的内容改变
        onContentChange() {
            // console.log(value); 第一个传入参数， 写的内容
            // console.log(render); 第二个传入参数， 实际的 html 文本内容
        },
        onEditorImageClick() {
            this.dialogVisible = true;
            this.imageSelectFor = 'article'
            this.listImages();
        },
        handleClose() {

        },
        listImages() {
            listImages(this.pageNavigation.currentPage,
                this.pageNavigation.pageSize,
                this.imageSelectFor).then(result => {
                if (result.code === success_code) {
                    this.$message.success(result.message);
                    this.articleImages = result.data.content;

                    this.pageNavigation.totalElements = result.data.totalElements;
                    this.pageNavigation.totalPages = result.data.totalPages;
                    this.pageNavigation.currentPage = result.data.currentPage;
                } else {
                    this.$message.error(result.message);
                }
            });
        },
        // 搜索页面大小改变的监听
        handleSizeChange(val) {
            this.pageNavigation.pageSize = val;
        }
        ,
        // 搜索页码改变的监听
        handleCurrentChange(val) {
            this.pageNavigation.currentPage = val;
            this.listImages();
        },
        // 点击打开选择文章封面
        choiceArticleCover() {
            this.dialogVisible = true;
            this.imageSelectFor = 'cover';
            this.listImages();
        },
        // 发表文章
        postAndPutArticle() {
            // check data
            if (this.article.title === '') {
                this.$message.warning("文章标题不能为空");
                return false;
            }
            if (this.article.content === '') {
                this.$message.warning("内容不能为空");
                return false;
            }
            if (this.labels.length === 0) {
                this.$message.warning("请输入标签，方便用户搜索");
            } else {
                let tempLabels = '';
                // complete submit data
                this.labels.forEach((item, index) => {
                    tempLabels += item;
                    if (index !== this.labels.length - 1) {
                        tempLabels += '-';
                    }
                });

                this.article.label = tempLabels;
            }
            this.$refs[this.formName].validate((valid) => {
                if (valid) {
                    // this.$refs[this.formName].resetFields();
                    // submit data
                    if (this.article.id === '') {
                        postArticle(this.article).then(result => {
                            if (result.code === success_code) {
                                this.$message.success("上传文章成功");

                            } else {
                                this.$message.error(result.message);
                                return false;
                            }
                        });
                    } else {
                        putArticle(this.article).then(result => {
                            if (result.code === success_code) {
                                this.$message.success("更新文章成功");

                            } else {
                                this.$message.error(result.message);
                                return false;
                            }
                        });
                    }
                } else {
                    return false;
                }
            });

            // change listener
            window.onbeforeunload = null;

            // change data
            this.article.state = '';
            this.isContentSave = true;
            // 界面跳转
            this.$router.push({
                path: '/content/manage-article'
            });
        },
        saveArticleDraft() {
            // complete data
            this.article.state = db_draft_state_article;
            let success = this.postAndPutArticle();

            if (success === false) {
                this.article.state = '';
            }
        },
        publicArticle() {
            // complete data
            this.article.state = db_publish_status;

            let success = this.postAndPutArticle();

            if (success === false) {
                this.article.state = '';
            }
        },
        // 点击全屏预览文章显示效果
        preView() {
            this.$refs.editor.toolbar_right_click('read');
        },
        // 获取文章信息用于更新 修改文章
        getArticle(_id) {
            getArticle(_id.toString()).then((result) => {
                if (result.code === success_code) {
                    let articleFromServer = result.data;

                    // change data
                    this.article.id = articleFromServer.id;
                    this.article.cover = articleFromServer.cover;
                    this.article.title = articleFromServer.title;
                    this.article.state = articleFromServer.state;
                    this.article.summary = articleFromServer.summary;
                    this.article.order = articleFromServer.order;
                    this.article.content = articleFromServer.content;
                    this.article.categoryId = articleFromServer.categoryId;
                    this.labels = articleFromServer.labels;
                } else {
                    this.$message.error("获取文章分类失败");
                }
            });
        },
        toNextPage() {
            this.saveConfirmDialogVisible = false;
            this.isContentSave = true;
            this.$router.push({
                path: this.nextPath
            })
        }
    },
    mounted() {
        // init variable
        let articleId = this.$route.query.articleId;

        // init listener
        // 关闭窗口前提示
        window.onbeforeunload = function () {
            return "系统可能不会保存填写的内容";
        }

        // init data
        if (articleId) {
            this.getArticle(articleId);
        }
        listCategories().then(result => {
            if (result.code === success_code) {
                this.categories = result.data;
            } else {
                this.$message.error("获取文章分类失败");
            }
        });

        this.listImages();
    },
    beforeDestroy() {
        window.onbeforeunload = null;
    },
    beforeRouteLeave(to, from, next) {
        if (this.isContentSave) {
            next();
        } else {
            this.nextPath = to.path;
            this.saveConfirmDialogVisible = true;
            console.log(next);
        }

    }
}
</script>

<style scoped>

.markdown-body {
    height: 800px;
}

.article-post-part {
    margin-top: 20px;
    color: red;
    background-color: #66ccff;
}

.article-post-settings-part {
    margin-top: 20px;
}

.article-post-action-bar {

}

.article-btn-container {
    float: right;
    margin-right: 50px;
    padding: 10px;
}


.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: #8c939d dashed 1px;
    border-radius: 4px;
}

.avatar-box {
    width: 178px;
    height: 178px;
    display: block;
}

.image-list-style {
    width: 150px;
    height: 150px;
    margin: 10px;
}

.image-selector-list {
    width: 100%;
    height: 100%;
}

.article-post-dialog-box {
    height: 100%;
}

.page-navigation-box {
    margin-top: 20px;
}
</style>